import { Button, Checkbox, Input, InputNumber, Space } from "antd";
import { useEffect, useState } from "react";

type Props = {
  defaultValue?: number;
  disabled?: boolean;
  onChange?: (value: number, checked: boolean) => void;
};
const App = (props: Props) => {
  const {
    disabled: defaultDisabled = false,
    defaultValue = 0,
    onChange = () => {},
  } = props;
  const [disabled, setDisabled] = useState(true);
  const [ckecked, setChecked] = useState(false);
  const [value, setValue] = useState(defaultValue);

  useEffect(() => {
    if (defaultValue > 0) {
      setChecked(true);
      setDisabled(false);
    } else {
      setChecked(false);
      setDisabled(true);
    }
    setTimeout(() => {
      setValue(defaultValue);
    }, 10);
  }, [defaultValue]);
  useEffect(() => {
    if (!ckecked) {
      setValue(0);
      setDisabled(true);
    } else {
      setDisabled(false);
    }
  }, [ckecked]);
  return (
    <Space.Compact>
      <Checkbox
        checked={ckecked}
        disabled={defaultDisabled}
        onChange={(e) => {
          console.log(e);
          setChecked(e.target.checked);
          setDisabled(!e.target.checked);
          //如果没有选中，清空输入框
          if (!e.target.checked) {
            setValue(0);
            onChange(0, e.target.checked);
          } else {
            onChange(value, e.target.checked);
          }
        }}
        style={{
          width: 200,
          verticalAlign: "middle",
          lineHeight: "30px",
        }}
      >
        价格优惠至
      </Checkbox>
      <InputNumber
        addonAfter="元"
        min={0}
        value={value}
        disabled={disabled || defaultDisabled}
        precision={2}
        onChange={(val) => {
          onChange(val as number, true);
          setValue(val as number);
        }}
        placeholder="填写金额"
      />
    </Space.Compact>
  );
};
export default App;
